package cn.sunxiansheng.log4j2.config;

import cn.sunxiansheng.log4j2.aspectj.LogAspect;
import cn.sunxiansheng.log4j2.aspectj.TraceIdLoggingAspect;
import cn.sunxiansheng.log4j2.config.properties.Log4j2Properties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * Description: Log4j2自动配置类
 *
 * @Author sun
 * @Create 2024/10/24 10:36
 * @Version 1.0
 */
@Configuration
@EnableConfigurationProperties({Log4j2Properties.class}) // 启用配置类
@Slf4j
public class Log4j2AutoConfiguration {

    /**
     * 自动配置成功日志
     */
    @PostConstruct
    public void logConfigSuccess() {
        log.info("Log4j2AutoConfiguration has been loaded successfully!");
    }

    /**
     * 条件注入LogAspect
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "sun-rays.log4j2.log-aspect-enable", havingValue = "true", matchIfMissing = true)
    LogAspect logAspect() {
        log.info("LogAspect 成功注入!");
        return new LogAspect();
    }

    /**
     * 条件注入链路追踪过滤器
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    TraceIdLoggingAspect traceIdLoggingAspect() {
        return new TraceIdLoggingAspect();
    }
}